package com.rd.student.jiaji.class2.shirui.day0728;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class Test2 {
    public static void main(String[] args) {
        String filename = "all.txt"; // 文件名
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入想要随机人的个数");
        int n = scanner.nextInt();


        List<String> students = readStudentsFromFile(filename);
        if (students != null) {
            List<String> selectedStudents = pickRandomStudents(students, n);
            System.out.println("随机选取的同学为:");
            for (String student : selectedStudents) {
                System.out.println(student);
            }
        }
    }


    public static List<String> readStudentsFromFile(String filename) {
        List<String> students = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = br.readLine()) != null) {
                students.add(line);
            }
        } catch (IOException e) {
            throw  new RuntimeException(e);

        }
        return students;
    }

    public static List<String> pickRandomStudents(List<String> students, int n) {

        List<String> selectedStudents = new ArrayList<>();
        Random random = new Random();
        List<String> tempList = new ArrayList<>(students);
        Collections.shuffle(tempList);
        for (int i = 0; i < n; i++) {
            selectedStudents.add(tempList.get(i));
        }
        return selectedStudents;
    }
}
